package com.yyb.utils;

import cn.hutool.http.useragent.UserAgent;
import cn.hutool.http.useragent.UserAgentUtil;
import jakarta.servlet.http.HttpServletRequest;
import org.springframework.util.ObjectUtils;
import org.springframework.util.StringUtils;

/**
 * 描述: [获取IP，浏览器，操作系统，浏览版本等等]
 * 
 * 
 */
public class HttpUtils {

    private HttpUtils(){

    }
    /**
     * 得到请求地址
     */
    public static String teRequestUrl(HttpServletRequest request){
        return request.getRequestURI();
    }

    /**
     * 得到浏览器名称
     */
    public static String getBrowserName(HttpServletRequest request){
        String header = request.getHeader("User-Agent");
        UserAgent ua = UserAgentUtil.parse(header);
        return ua.getBrowser().toString();
    }
    /**
     * 得到浏览器的版本
     */
    public static String getBrowserVersion(HttpServletRequest request){
        String header = request.getHeader("User-Agent");
        UserAgent ua = UserAgentUtil.parse(header);
        return ua.getVersion();
    }
    /**
     * 得到操作系统的名称
     */
    public static String getOsName(HttpServletRequest request){
        String header = request.getHeader("User-Agent");
        UserAgent ua = UserAgentUtil.parse(header);
        return ua.getOs().toString();
    }

    /**
     * 得到IP 地址
     */
    public static String getIpAddr(HttpServletRequest request){
        if(ObjectUtils.isEmpty(request)){
            return "unknown";
        }else{
            String ip=request.getHeader("x-forwarded-for");
            if(!StringUtils.hasText(ip)||"unknown".equalsIgnoreCase(ip)){
                ip =request.getHeader("Proxy-Client-IP");
            }
            if(!StringUtils.hasText(ip)||"unknown".equalsIgnoreCase(ip)){
                ip =request.getHeader("X-Forwarded-For");
            }
            if(!StringUtils.hasText(ip)||"unknown".equalsIgnoreCase(ip)){
                ip =request.getHeader("WL-Proxy-Client-IP");
            }
            if(!StringUtils.hasText(ip)||"unknown".equalsIgnoreCase(ip)){
                ip =request.getHeader("X-Real-IP");
            }
            if(!StringUtils.hasText(ip)||"unknown".equalsIgnoreCase(ip)){
                ip =request.getRemoteAddr();
            }
            if("0:0:0:0:0:0:0:1".equalsIgnoreCase(ip)){
                ip="127.0.0.1";
            }
            if(ip.contains(",")){
                ip=ip.split(",")[0];
            }
            return ip;
        }
    }

}
